package factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
* bean工厂
*/
public class BeanFactory {
   //定义一个Properties对象
   private static Properties properties;

   //通过静态代码块为Properties对象赋值
   static {
       try {
           //实例化对象
           properties = new Properties();
           //获取properties文件的流对象
           InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
           properties.load(in);
      } catch (IOException e) {
           throw new ExceptionInInitializerError("初始化properties失败");
      }
  }
   /**
    * 根据bean名称获取bean对象
    * @param beanName
    * @return
    */
   public static Object getBean(String beanName){
       Object bean = null;
       //根据bean名称获取bean的全类名
       String beanPath = properties.getProperty(beanName);
       try {
           //使用全类名通过反射创建实例
           bean = Class.forName(beanPath).newInstance();
      } catch (Exception e) {
           e.printStackTrace();
      }
       return bean;
  }
}